﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace codeAnalyzer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void btnSelectFile_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                //用filter限制用户所能选择的文件类型 
                Filter = "C# Source Files (*.cs)|*.cs"//*.cs表示只显示拓展名为.cs的文件
            };
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFileDialog.FileName;
                txtFilePath.Text = filePath;
                ProcessFile(filePath);
            }

        }
        //处理文件 统计行数和单词数
        private void ProcessFile(string filePath)
        {
            try
            {
                string[] lines = File.ReadAllLines(filePath);

                //统计行数
                int totalLines = lines.Length;
                int nonEmptyLines = lines.Count(line => !string.IsNullOrWhiteSpace(line));

                //统计单词数
                string fileContent = File.ReadAllText(filePath);
                string cleanedContent = Regex.Replace(fileContent, @"[^\w\s]", "");//移除所有标点符号
                int wordCount = cleanedContent.Split(new[] { ' ', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries).Length;
                string[] words = cleanedContent.Split(new[] { ' ', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                //分割单词后 使用dictionary统计每个单词的出现次数
                Dictionary<string, int> wordCnt = new Dictionary<string, int>();
                foreach (string word in words)
                {
                    if (wordCnt.ContainsKey(word))
                    {
                        wordCnt[word]++;
                    }
                    else
                    {
                        wordCnt.Add(word, 1);
                    }
                }
                listboxWordCnt.Items.Clear();
                foreach (var entry in wordCnt.OrderByDescending(entry => entry.Value))
                {
                    listboxWordCnt.Items.Add($"{entry.Key}:{entry.Value}次");
                }

                txtTotalLine.Text = "原始行数" + totalLines.ToString();
                txtNonEmptyLines.Text = "有效行数" + nonEmptyLines.ToString();
                txtWordCount.Text = "单词数" + wordCount.ToString();


            }
            catch (Exception ex)
            {
                MessageBox.Show("error");
            }
        }

        private void button1_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog
            {
                //用filter限制用户所能选择的文件类型 
                Filter = "C# Source Files (*.cs)|*.cs"//*.cs表示只显示拓展名为.cs的文件
            };
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                string filePath = openFileDialog.FileName;
                txtFilePath.Text = filePath;
                ProcessFile1(filePath);
            }
        }

        private void ProcessFile1(string filePath)
        {
            try
            {
                string[] lines = File.ReadAllLines(filePath);

                // 过滤掉空行和以 "//" 开头的注释行
                var validLines = lines
                    .Where(line => !string.IsNullOrWhiteSpace(line))  // 去掉空行
                    .Where(line => !line.TrimStart().StartsWith("//")) // 去掉注释行
                    .ToArray();

                // 统计有效行数
                int nonEmptyNonCommentLines = validLines.Length;

                // 统计单词数（排除标点符号）
                string validContent = string.Join(" ", validLines); // 将有效行合并成一个字符串
                string cleanedContent = Regex.Replace(validContent, @"[^\w\s]", ""); // 删除标点符号
                int wordCount = cleanedContent
                    .Split(new[] { ' ', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries)
                    .Length;
                string[] words = cleanedContent.Split(new[] { ' ', '\r', '\n' }, StringSplitOptions.RemoveEmptyEntries);
                //分割单词后 使用dictionary统计每个单词的出现次数
                Dictionary<string, int> wordCnt = new Dictionary<string, int>();
                foreach (string word in words)
                {
                    if (wordCnt.ContainsKey(word))
                    {
                        wordCnt[word]++;
                    }
                    else
                    {
                        wordCnt.Add(word, 1);
                    }
                }
                listboxWordCnt.Items.Clear();
                foreach (var entry in wordCnt.OrderByDescending(entry => entry.Value))
                {
                    listboxWordCnt.Items.Add($"{entry.Key}:{entry.Value}次");
                }
                // 显示统计结果
                txtTotalLine.Text = "原始行数" + lines.Length.ToString();  // 原始行数
                txtNonEmptyLines.Text = "有效行数" + nonEmptyNonCommentLines.ToString();  // 有效行数（去掉空行和注释行）
                txtWordCount.Text = "单词数" + wordCount.ToString();  // 有效单词数

            }
            catch (Exception ex)
            {
                MessageBox.Show($"文件处理时出错: {ex.Message}");
            }
        }
    }
}
